package com.mmall.controller.backend;

import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.pojo.User;
import com.mmall.service.IFileService;
import com.mmall.service.IProductService;
import com.mmall.service.IUserService;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Create by lisy on Qingdao
 **/

@RequestMapping(value="/manage/product")
@Controller
public class ProductManagerController {

    @Autowired
    IUserService iUserService;

    @Autowired
    IProductService iProductService;
    @Autowired
    IFileService iFileService;
    /**
     * ####6.新增OR更新产品
     * 新增
     * 新增 http://localhost:8080/manage/product/save.do?categoryId=1&name=三星洗衣机&subtitle=三星大促销&subImages=test.jpg,11.jpg,2.jpg,3.jpg&detail=detailtext&price=1000&stock=100&status=1
     * 更新 http://localhost:8080/manage/product/save.do?categoryId=1&name=三星洗衣机&subtitle=三星大促销&subImages=test.jpg&detail=detailtext&price=1000&stock=100&status=1&id=3
     * /manage/product/save.do
     */
    @RequestMapping(value = "save.do", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse productSave(HttpSession session, Product product){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        //判断用户是否登录
        if(user == null){
            return ServerResponse.createByErrorMssage("用户未登录");
        }
        //判断管理员权限
        ServerResponse response = iUserService.checkUserRole(user);
        if(response.isSuccess()){
            //用户是管理员开始执行方法
            //调用Service方法，添加商品
            return iProductService.productSaveOrAddService(product);
        } else {
            return ServerResponse.createByErrorMssage("无权操作");
        }
    }


    /**
     * ####5.产品上下架
     * http://localhost:8080/manage/product/set_sale_status.do?productId=1&status=1
     * /manage/product/set_sale_status.do
     */
    @RequestMapping(value = "set_sale_status.do", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse setSaleStatus(HttpSession session, Integer productId, Integer status){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorMssage("用户未登录权限");
        }
        ServerResponse response = iUserService.checkUserRole(user);
        if(response.isSuccess()){
            //用户是管理员
            return iProductService.setSaleStatusService(productId, status);
        }else {
            return ServerResponse.createByErrorMssage("无权限操作");
        }
    }

    /**
     * ####4.产品详情
     * http://localhost:8080/manage/product/detail.do?productId=2
     * /manage/product/detail.do
     */
    @RequestMapping(value="detail.do", method=RequestMethod.GET)
    @ResponseBody
    public ServerResponse getDetail(HttpSession session, Integer productId){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorMssage("用户未登录权限");
        }
        ServerResponse response = iUserService.checkUserRole(user);
        if(response.isSuccess()){
            //用户是管理员，进行取商品操作
            return iProductService.getProductDetail(productId);
        }else {
            return ServerResponse.createByErrorMssage("无权限操作");
        }
    }

    /**
     * ####1.产品list
     * http://localhost:8080/manage/product/list.do
     * /manage/product/list.do
     */
    @RequestMapping(value = "list.do")
    @ResponseBody
    public ServerResponse listProduct(HttpSession session,
                                      @RequestParam(value="pageNum", defaultValue = "1")int pageNum,
                                      @RequestParam(value="pagSize", defaultValue = "10") int pageSize){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorMssage("用户未登录权限");
        }
        ServerResponse response = iUserService.checkUserRole(user);
        if(response.isSuccess()){
            //用户是管理员
            return iProductService.selectAllProduct(pageNum, pageSize);
        }else {
            return ServerResponse.createByErrorMssage("无权限操作");
        }
    }

    /**
     * ####2.产品搜索
     * http://localhost:8080/manage/product/search.do?productName=p
     * http://localhost:8080/manage/product/search.do?productId=1
     * /manage/product/search.do
     */
    @RequestMapping(value="search.do")
    @ResponseBody
    public ServerResponse productSearch(HttpSession session, String productName, Integer productId,
                                        @RequestParam(value="pageNum", defaultValue = "1")int pageNum,
                                        @RequestParam(value="pagSize", defaultValue = "10") int pageSize){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorMssage("用户未登录权限");
        }
        ServerResponse response = iUserService.checkUserRole(user);
        if(response.isSuccess()){
            //用户是管理员
            return iProductService.productSearch(productName, productId, pageNum, pageSize);
        }else {
            return ServerResponse.createByErrorMssage("无权限操作");
        }
    }

    /**
     * ####3.图片上传
     * /manage/product/upload.do
     */
    @RequestMapping("upload.do")
    @ResponseBody
    public ServerResponse upload(HttpSession session, @RequestParam(value="upload_file", required = false) MultipartFile file,
                                 HttpServletRequest request){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorMssage("用户未登录权限");
        }
        ServerResponse response = iUserService.checkUserRole(user);
        if(response.isSuccess()){
            //用户是管理员
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file, path);
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;

            Map fileMap = new HashMap();
            fileMap.put("uri", targetFileName);
            fileMap.put("url", url);
            return ServerResponse.createBySuccess(fileMap);
        }else {
            return ServerResponse.createByErrorMssage("无权限操作");
        }
    }

    /**
     * 富文本上传图片
     */
    @RequestMapping("reachtext_img_upload.do")
    @ResponseBody
    public Map reachtextImgUpload(HttpSession session, @RequestParam(value="upload_file", required = false) MultipartFile file,
                                  HttpServletRequest request, HttpServletResponse response){
        Map resultMap = Maps.newHashMap();
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            resultMap.put("success", false);
            resultMap.put("msg", "请登录管理员");
            return resultMap;
        }
        //富文本中返回值 使用simditor

        ServerResponse serverResponse = iUserService.checkUserRole(user);
        if(serverResponse.isSuccess()){
            //用户是管理员
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file, path);
            if(StringUtils.isBlank(targetFileName)){
                resultMap.put("success", false);
                resultMap.put("msg", "上传失败");
                return resultMap;
            }
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
            resultMap.put("success", false);
            resultMap.put("msg", "上传成功");
            resultMap.put("file_path", url);
            response.addHeader("Access-Control-Allow-Headers", "X-File-Name");
            return resultMap;

        }else {
            resultMap.put("success", false);
            resultMap.put("msg", "无权限操作");
            return resultMap;
        }
    }
}
